﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Threading;

namespace ScreenShare1
{
    /// <summary>
    /// Interaction logic for Client.xaml
    /// </summary>
    public partial class Client : Window
    {
        public Client()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            //NetTcpBinding binding = new NetTcpBinding();
            //binding.MaxReceivedMessageSize = 1000000000;
            //binding.MaxBufferSize = 1000000000;
            //binding.ReaderQuotas.MaxArrayLength = 1000000000;

            System.ServiceModel.Channels.Binding binding = Utils.CreateBinding();

            //EndpointAddress address = new EndpointAddress("net.tcp://PC2139X:31415/ScreenShare");
            
            //IContract channel = ChannelFactory<IContract>.CreateChannel(binding, address);
            //channel.Ping();

            ChannelFactory<IContract> factory = new ChannelFactory<IContract>(binding, "net.tcp://bld08:31415/ScreenShare");
            channel = factory.CreateChannel();
            
            channel.Ping();

            Thread continuousReadThread = new Thread(new ThreadStart(LoadScreen));
            continuousReadThread.IsBackground = true;
            continuousReadThread.Start();
        }

        private void LoadScreen()
        {
            while (!stopped)
            {
                byte[] pictureBuffer = channel.GetPicture();

                if (isReady)
                    Dispatcher.BeginInvoke((Action<byte[]>)RenderImage, pictureBuffer);
            }
        }

        bool stopped = false;

        bool isReady = true;

        

        private void RenderImage(byte[] pictureBuffer)
        {
            isReady = false;
            Picture = LoadImage(pictureBuffer);
            image.Source = Picture;
            isReady = true;
        }


        IContract channel = null;

        public BitmapSource Picture { get; set; }

        BitmapSource LoadImage(Byte[] imageData)
        {
            using (MemoryStream ms = new MemoryStream(imageData))
            {
                var decoder = BitmapDecoder.Create(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); 
                return decoder.Frames[0];
            }
        }
    }
}

